<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "sys_auth".
 *
 * @property int $authid
 * @property string|null $app_code
 * @property string|null $app_secret
 * @property string|null $auth_key
 * @property string|null $access_token
 * @property int|null $token_utc
 * @property int $allowance
 * @property int $allowance_updated_at
 */
class SysAuth extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'sys_auth';
    }

    public function attributes()
    {
        return ['authid','app_code','app_secret','auth_key','access_token','token_utc','allowance','allowance_updated_at'];
    }
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['token_utc', 'allowance', 'allowance_updated_at'], 'integer'],
            [['app_code', 'app_secret', 'auth_key', 'access_token'], 'string', 'max' => 50],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'authid' => 'AuthId',
            'app_code' => 'App Code',
            'app_secret' => 'App Secret',
            'auth_key' => 'Auth Key',
            'access_token' => 'Access Token',
            'token_utc' => 'Token UTC',
            'allowance' => 'Allowance',
            'allowance_updated_at' => 'Allowance Updated At',
        ];
    }

    public static function getAuthById($id)
    {
        return self::find()->where(['deleteflag' => 0,'authid'=>$id])->one();
    }

    public static function getAuthByToken($token)
    {

        return self::find()->where(['deleteflag' => 0,'access_token'=>$token])->one();
    }

    public function getToken()
    {

        $rd_auth = $this->find()->where(['deleteflag' => 0,'app_code'=>$this->app_code,'app_secret'=>$this->app_secret])->one();

        if($rd_auth == null){
            return false;
        }
        $rd_auth->token_utc = gmdate('U')+60*60*24;
        $rd_auth->access_token = md5($rd_auth['authid'].$rd_auth['app_code'].$rd_auth->token_utc.'access_token_secret');
        if($rd_auth->update() !== false ){
            return [
                'access_token'=>$rd_auth->access_token,
                'token_utc' =>$rd_auth->token_utc
            ];
        }else{
            return false;
        }

    }


}
